﻿using Model;
using Model.Enum;
using MQTTTool.Page.Mqtt;
using MQTTTool.Static;
using MQTTTool.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MQTTTool.Controls
{
	public partial class MqttPage : UserControl
	{
		public MQConfig config = new MQConfig();
		public MQTTUtil Mqttutil;//发送消息的
		bool loopsend;//是否使用循环发送
		bool issending = false;//是否正在循环发送
		bool waitresult = true;//是否等待结果再循环
		public MqttPage()
		{
			InitializeComponent();

		}
		public MqttPage(MQConfig config)
		{
			InitializeComponent();
			Mqttutil = new MQTTUtil  (config, this);
			this.config = config;
			InitData();
		}

		private void InitData()
		{
			integerInput_starti.Value = config.nowindex;
			textBoxX_data.Text = config.SendMsg;
			integerInput_stream.Value= config.streamlength;
			integerInput_waittime.Value = config.waittime;
		}

		/// <summary>
		/// 写日志
		/// </summary>
		/// <param name="logstr"></param>
		public void AddLog(string logstr, LogEnum logtype)
		{
			try
			{

				logstr = DateTime.Now.ToLocalTime() + " " + logstr;
				if (InvokeRequired)
				{
					this.Invoke(new ThreadStart(delegate
					{
						this.Log(logstr, logtype);

					}));
				}
				else
				{
					this.Log(logstr, logtype);


				}
			}
			catch (Exception)
			{
				this.textBoxX_Log.Clear();
			}
		}

		private void Log(string logstr, LogEnum logtype) {
			switch (logtype)
			{
				case LogEnum.SendLog:
					this.textBoxX_Log.AppendTextColorful(logstr,Color.Blue);

					break;
				case LogEnum.ReceverLog:

					this.textBoxX_Log.AppendTextColorful(logstr, Color.Green);
					break;
				case LogEnum.ErrLog:
					this.textBoxX_Log.AppendTextColorful(logstr, Color.Red);
					break;
				default:
					this.textBoxX_Log.AppendTextColorful(logstr, Color.Black);
					break;
			}
		}
		private void buttonX2_Click(object sender, EventArgs e)
		{
			MqttConfigPage cpage = new MqttConfigPage(config);
			if (cpage.ShowDialog().Equals(DialogResult.OK))
			{
				Mqttutil = new MQTTUtil(config, this);
			}

		}

		private void checkBoxX1_CheckedChanged(object sender, EventArgs e)
		{
			loopsend = this.checkBoxX_loop.Checked;
		}
		Task main;
		private void buttonX1_Click(object sender, EventArgs e)
		{
			if (main != null)
			{
				return;
			}
			try
			{
				main = Task.Run(() =>
						{
							try
							{
								if (loopsend)
								{
									try
									{
										//循环发送逻辑
										issending = true;
										int value = integerInput_starti.Value;
										for (int i = 0; issending && i < integerInput_loopcount.Value; i++, integerInput_starti.Value++)
										{
											string msg = "";
											this.Invoke(new ThreadStart(delegate
											{
												msg = textBoxX_data.Text;
												string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
												msg = msg.Replace(textBoxX_time.Text, nowTime);
												string stream = GetStream(integerInput_stream.Value, i + value);
												msg = msg.Replace(textBoxX_loopstr.Text, stream);
												
											}));

											if (waitresult)
											{
												Mqttutil.SendMsgAndGetResult(msg, integerInput_timeout.Value);
												AddLog("发送消息:" + msg, LogEnum.SendLog);
											}
											else
											{
												Mqttutil.Mqtt(msg);

											}
											Thread.Sleep(integerInput_waittime.Value);
										}

									}
									catch (Exception ex)
									{
										AddLog(ex.Message + ex.StackTrace,LogEnum.ErrLog);

									}
									finally
									{
										issending = false;
									}
								}
								else
								{
									//普通发送逻辑

									string msg = "";
									this.Invoke(new ThreadStart(delegate
									{
										msg = textBoxX_data.Text;
										string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
										msg = msg.Replace(textBoxX_time.Text, nowTime);
										AddLog("发送消息:" + msg, LogEnum.SendLog);
									}));
									string result = Mqttutil.SendMsgAndGetResult(msg, integerInput_timeout.Value);
									//AddLog("收到消息:" + result);

								}
							}
							catch (Exception ex)
							{
								AddLog(ex.Message + ex.StackTrace, LogEnum.ErrLog);

							}
							finally
							{
								main = null;
							}

						});
			}
			catch (Exception ex )
			{

				AddLog(ex.Message + ex.StackTrace,LogEnum.ErrLog);

			}
			finally {
				main = null;
			}
		}
		/// <summary>
		/// s生成流水码
		/// </summary>
		/// <param name="length">流水码长度</param>
		/// <param name="data">数据位</param>
		/// <returns></returns>
		private string GetStream(int length, int data)
		{
			string stream = data + "";
			int len = stream.Length;
			for (int j = 0; j < length - len; j++)
			{
				stream = "0" + stream;
			}
			return stream;
		}

		private void buttonX_stop_Click(object sender, EventArgs e)
		{
			issending = false;
		}

		private void checkBoxX_waitr_CheckedChanged(object sender, EventArgs e)
		{
			waitresult = checkBoxX_waitr.Checked;
		}

		private void buttonX_insertloopstr_Click(object sender, EventArgs e)
		{
			int str = textBoxX_data.SelectionStart;
			textBoxX_data.Text = textBoxX_data.Text.Insert(str, textBoxX_loopstr.Text);
		}

		private void buttonX_Inserttimestr_Click(object sender, EventArgs e)
		{
			int str = textBoxX_data.SelectionStart;
			textBoxX_data.Text = textBoxX_data.Text.Insert(str, textBoxX_time.Text);
		}

		private void textBoxX_data_TextChanged(object sender, EventArgs e)
		{
			config.SendMsg = textBoxX_data.Text;
		}

		private void integerInput_waittime_ValueChanged(object sender, EventArgs e)
		{
			config.waittime = integerInput_waittime.Value;
		}

		private void integerInput_stream_ValueChanged(object sender, EventArgs e)
		{
			config.streamlength = integerInput_stream.Value;

		}

		private void integerInput_starti_ValueChanged(object sender, EventArgs e)
		{
			config.nowindex = integerInput_starti.Value;

		}

		private void integerInput_timeout_ValueChanged(object sender, EventArgs e)
		{
			config.waittime = integerInput_waittime.Value;

		}
	}
}
